package kr.co.graviti.sqlmap;

import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.sql.CLOB;

import com.ibatis.sqlmap.engine.type.BaseTypeHandler;
import com.ibatis.sqlmap.engine.type.TypeHandler;

public class OracleClobStringTypeHandler extends BaseTypeHandler implements TypeHandler{
	
	public void setParameter(PreparedStatement ps, int i, Object parameter
			, String jdbcType) throws SQLException {
		String value = (String) parameter;
		if (value != null) {
			CLOB clob = CLOB.createTemporary(ps.getConnection(), true
				, CLOB.DURATION_SESSION);
			clob.putChars(1, value.toCharArray());
			ps.setClob(i, clob);
		} else {
			ps.setString(i, null);
		}
	}

	public Object getResult(ResultSet rs, String columnName)
			throws SQLException {
		Clob clob = rs.getClob(columnName);
		if (rs.wasNull()) {
			return null;
		} else {
			return clob.getSubString(1, (int) clob.length());
		}
	}

	public Object getResult(ResultSet rs, int columnIndex)
			throws SQLException {
		Clob clob = rs.getClob(columnIndex);
		if (rs.wasNull()) {
			return null;
		} else {
			return clob.getSubString(1, (int) clob.length());
		}
	}

	public Object getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		Clob clob = cs.getClob(columnIndex);
		if (cs.wasNull()) {
			return null;
		} else {
			return clob.getSubString(1, (int) clob.length());
		}
	}

	public Object valueOf(String s) {
		return s;
	}
	
}
